//
//  CZOauthViewController.swift
//  Weibo
//
//  Created by 铭铭 on 15/11/27.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

import SVProgressHUD

class CZOauthViewController: UIViewController {

    
    override func loadView() {
        //不用设置约束
        view = webView
        
      webView.delegate=self
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        

        
        // 设置导航栏
        // 左边
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        
        // 右边
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        // 加载授权登录页面
        let request = NSURLRequest(URL: CZNetworkTool.sharedInsatance.oauthURL())
            webView.loadRequest(request)
    }

    /// 填充账号
    func autoFill(){
        // 创建js代码
        let js = "document.getElementById('userId').value='785089158@qq.com'; document.getElementById('passwd').value='52013144836';"
        // 让webView执行js代码
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    /// 关闭控制器
    func close() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
//    /// 加载accessToken
    func loadAccessToken(code:String){
        CZNetworkTool.sharedInsatance.loadAccessToken(code) { (result, error) -> () in
            
            // 判断是否有错误.有错误,提示用户,关闭控制器
            if error != nil || result == nil{
//            
//                 // 告诉用户出错
               SVProgressHUD.showErrorWithStatus("你的网络不给力", maskType: SVProgressHUDMaskType.Black)
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                    self.close()
                })
                return
            }
             // 没有出错,保存数据
        let account = CZUserAccount(dict: result!)
//
            // 保存对象
            account.saveAccount()
         
        }
    }

//MARK:-- 懒加载
    private lazy var webView = UIWebView()

}

//MARK: -扩展 CZOauthViewController 实现 UIWebViewDelegate 协议
extension CZOauthViewController: UIWebViewDelegate{
    /// webView开始加载链接
    func webViewDidStartLoad(webView:UIWebView){
        
        SVProgressHUD.showWithStatus("正在加载...", maskType: SVProgressHUDMaskType.Black)

    }
    /// webView加载完成某个链接
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    
    // webView加载链接,每当webView加载一个链接都会通过这个代理方法来询问我们这个地址是否可以加载 true表示可以加载, false 就不加载.
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        

        
        let urlString = request.URL!.absoluteString
        
        // 如果加载的不是授权回调页面,直接加载网页,
        // 如果加载的是授权回调页面,对后面的参数进行判断,如果有code=表示点击了授权按钮,否则点击取消

         // 当用户点击取消或同意,拦截,不让它加载,我们来处理, // 其他情况, 直接加载
        if !(urlString.hasPrefix(CZNetworkTool.sharedInsatance.redirect_uri)) {
            return true
        }
        
         print("回调地址: \(request.URL?.query)")
        
        // 判断url地址里面是以code=开头,截取code= 后面的字符串
        if let query = request.URL?.query{
            
            let codeString = "code="
            
            // 判断query里面是否包含code=字符串
            if !query.hasPrefix(codeString){
                // 点击授权, 截取code的值
                let nsQuery = query as NSString

                let code  = nsQuery.substringFromIndex(codeString.characters.count)
                //  加载accessToken
                loadAccessToken(code)
       
                
            }else{// 点击取消
                 print("点击取消")
              self.close()
                
            }
        }
    // 不去加载授权回调地址
        return false
    }
}
